package com.singleton;

/**
 * 懒汉式
 */
public class Singleton3 {

    // 1. 构造方法私有化
    private Singleton3() {
    }
//2、然后声明一个静态变量保存单例的引用
    public static  volatile Singleton3 singleton1 = null;

    //3.静态方法获取实例
    ////不安全的
    public static  Singleton3 getInstance(){
        if (singleton1==null){
            synchronized (Singleton3.class){
                if (singleton1==null){
                    singleton1=new Singleton3();
                }
            }
        }
        return singleton1;
    }
}

class testSingleton3{
    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Singleton3.getInstance().hashCode());
                }
            }).start();
        }
    }
}
